import { defineStore } from 'pinia'
import { getUserInfo } from '../api/modules/user'
import { showFailToast } from 'vant'
// const router = useRouter()
export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userid: '', // 用户id
      userInfo: null, // 用户信息
      curContactId: '' // 当前联系人
    }
  },
  actions: {
    setUserId(id) {
      this.userid = id
    },
    setUserInfo(info) {
      this.userInfo = info
    },
    setCurContact(curContactId) {
      this.curContactId = curContactId
    },
    // 获取用户信息
    async getUserInfo() {
      try {
        const { data } = await getUserInfo()
        if (data.code === '10100') {
          // console.log('获取用户信息成功', data)
          this.setUserInfo(data.data)
          return data
        } else {
          showFailToast(data.message)
          return data
        }
      } catch ({ response: { data } }) {
        if (data.code === '10101') {
          return {
            code: '10101'
          }
        }
      }
    },

    // 退出登录
    logout() {
      localStorage.removeItem('token')
      this.setUserInfo(null)
      this.setUserId('')
    }
  },
  // 开始数据持久化
  persist: true
})
